import 'package:fish_redux/fish_redux.dart';
import 'package:flutter/material.dart' hide Action;
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hayll_app_village_master/hayll/network/yll_network.dart';
import 'package:hayll_app_village_master/hayll/village_manager/home/village_access_robbit_component/bean/robbit_app_version.dart';
import 'package:hayll_app_village_master/hayll/village_manager/home/village_access_robbit_component/bean/village_access_robbit.dart';
import 'package:hayll_app_village_master/hayll/village_manager/home/village_simple_component/action.dart';
import 'package:hayll_app_village_master/hayll/village_manager/network/village_action.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'action.dart';
import 'state.dart';

Effect<VillageAccessRobbitState> buildEffect() {
  return combineEffects(<Object, Effect<VillageAccessRobbitState>>{
    VillageAccessRobbitAction.action: _onAction,
    VillageAccessRobbitAction.updateAccessRobbit: _updateAccessRobbit,
    VillageAccessRobbitAction.scanDeviceLog: _scanDeviceLog,
    Lifecycle.initState: _initState,
    VillageAccessRobbitAction.activeDeviceVoip: _activeDeviceVoip,
    VillageAccessRobbitAction.rebootDevice: _rebootDevice,
    VillageAccessRobbitAction.changeDeviceValue: _changeDeviceValue,
    VillageAccessRobbitAction.saveDeviceValue: _saveDeviceValue,
    VillageAccessRobbitAction.getDeviceAllVersion: _getRobbitVersion,
    VillageAccessRobbitAction.updateDeviceVersion: _updateRobbitVersion,
    VillageAccessRobbitAction.deleteDevice: _deleteDevice,
    VillageAccessRobbitAction.registerDevice: _openAddingRobbitPage,
    VillageSimpleAction.chooseHouseChanged: _updateAccessRobbit,
  });
}

void _onAction(Action action, Context<VillageAccessRobbitState> ctx) {}

void _initState(Action action, Context<VillageAccessRobbitState> ctx) {
  ctx.dispatch(VillageAccessRobbitActionCreator.updateAccessRobbit());
  ctx.dispatch(VillageAccessRobbitActionCreator.getDeviceAllVersion());
}

void _updateAccessRobbit(
    Action action, Context<VillageAccessRobbitState> ctx) async {
  var sp = await SharedPreferences.getInstance();
  var lastVillageId = sp.getInt('lastVillage');
  var params = Map<String, dynamic>();
  if (ctx.state.unit != null && ctx.state.unit.itemId > 0) {
    params['targetId'] = ctx.state.unit.itemId;
    params['targetType'] = 3; //1:小区 2：楼栋 3：单元
  } else if (ctx.state.build != null && ctx.state.build.buildingId > 0) {
    params['targetId'] = ctx.state.build.buildingId;
    params['targetType'] = 2; //1:小区 2：楼栋 3：单元
  } else {
    params['targetId'] = lastVillageId;
    params['targetType'] = 1; //1:小区 2：楼栋 3：单元
  }

  params['pageNum'] = 1;
  params['pageSize'] = 999;
  params['termId'] = '';
  params['switchType'] = '';

  YllNetwork.requestPost(VillageAction.getVillageAccessRobbitList,
      params: params, success: (json) {
    ctx.state.robbitList.clear();
    var result = VillageAccessRobbitListResult.fromJson(json);
    if (result.data != null) {
      ctx.state.robbitList.addAll(result.data);
    }
    _matchRobbitVersion(action, ctx);
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _scanDeviceLog(Action action, Context<VillageAccessRobbitState> ctx) {
  int deviceId = action.payload;
  var deviceName = '';
  var deviceNo = '';
  for (var item in ctx.state.robbitList) {
    if (item.switchId == deviceId) {
      deviceName = item.switchName != null
          ? item.switchName
          : (item.location != null) ? item.location : '未命名';
      deviceNo = item.termId;
    }
  }
  Navigator.pushNamed(ctx.context, '/device_log',
      arguments: {'deviceNo': deviceNo, 'deviceName': deviceName});
}

void _activeDeviceVoip(Action action, Context<VillageAccessRobbitState> ctx) {
  YllNetwork.requestPost(VillageAction.activeDeviceVoip, params: action.payload,
      success: (json) {
    //获取结果
    // var success = json['data'] as
    var switchId = action.payload['switchId'];
    for (var item in ctx.state.robbitList) {
      if (item.switchId == switchId) {
        if (item.activeStatus) {
          item.activeStatus = false;
          item.activeStatusDesc = '未激活';
        } else {
          item.activeStatus = true;
          item.activeStatusDesc = '已激活';
        }
      }
    }
    ctx.dispatch(VillageAccessRobbitActionCreator.refreshUI());
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _rebootDevice(Action action, Context<VillageAccessRobbitState> ctx) {
  var params = {'termId': action.payload, 'command': 'reboot', 'param': {}};
  YllNetwork.requestPost(VillageAction.sendCommand, params: params,
      success: (json) {
    //获取结果
    // var success = json['data'] as
    Fluttertoast.showToast(msg: '操作成功');
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _changeDeviceValue(Action action, Context<VillageAccessRobbitState> ctx) {
  var deviceNo = action.payload['deviceNo'];
  var params = action.payload['params'] as Map<String, dynamic>;
  for (var item in ctx.state.robbitList) {
    if (item.termId == deviceNo) {
      if (params.containsKey('faceScore')) {
        item.recogniteLevel = params['faceScore'];
      }
      if (params.containsKey('unlockTime')) {
        item.unlocktime = (params['unlockTime'] as double).toInt();
      }
      ctx.dispatch(VillageAccessRobbitActionCreator.refreshUI());
    }
  }
}

void _saveDeviceValue(Action action, Context<VillageAccessRobbitState> ctx) {
  var deviceNo = action.payload;
  for (var item in ctx.state.robbitList) {
    if (item.termId == deviceNo) {
      var params = {
        'termId': deviceNo,
        'command': 'setup',
        'deviceTypeNo': 2,
        'param': {
          'luminance': item.luminance,
          'volume': item.volume,
          'limitsFacedUserCount': item.limitsFacedUserCount,
          'unlocktime': item.unlocktime,
          'passKey': item.passKey,
          'recogniteLevel': item.recogniteLevel,
        },
      };
      YllNetwork.requestPost(VillageAction.sendCommand, params: params,
          success: (json) {
        //获取结果
        // var success = json['data'] as
        Fluttertoast.showToast(msg: '设置成功');
      }, failed: (errorCode, errorMsg) {
        Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
      });
    }
  }
}

void _getRobbitVersion(Action action, Context<VillageAccessRobbitState> ctx) async{
  var params = {'productType': "DOORAPP", 'pageNum': 1, 'pageSize': 1000};
  YllNetwork.requestPost(VillageAction.getRobbitAppVersion, params: params,
      success: (json) {
    var versionList = RobbitAppVersionListResult.fromJson(json);
    if (versionList.data != null) {
      versionList.data.sort((left, right) {
        return right.versionId.compareTo(left.versionId);
      });
      ctx.state.versions = versionList.data;
      _matchRobbitVersion(action, ctx);
    }
  }, failed: (errorCode, errorMsg) async {
    // Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
    await Future.delayed(Duration(seconds: 3));
    ctx.dispatch(VillageAccessRobbitActionCreator.getDeviceAllVersion());
  });
}

void _updateRobbitVersion(
    Action action, Context<VillageAccessRobbitState> ctx) {
  var params = {
    'termId': action.payload['deviceNo'],
    'command': "updateVersion",
    'param': {'versionId': action.payload['versionId']}
  };
  YllNetwork.requestPost(VillageAction.sendCommand, params: params,
      success: (json) {
    //{"data":"错误:版本信息缓存不存在"}
    //获取结果
    // var success = json['data'] as
    Fluttertoast.showToast(msg: '操作成功');
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _matchRobbitVersion(Action action, Context<VillageAccessRobbitState> ctx) {
  ctx.state.robbitList.forEach((robbit) {
    if (robbit.appVersion != null) {
      for (var version in ctx.state.versions) {
        if (version.version.toLowerCase().contains('v')) {
          version.version = version.version.toLowerCase().replaceFirst('v', '');
        }
        if (version.version.compareTo(robbit.appVersion) > 0) {
          robbit.lastAppVersion = version;
          break;
        }
      }
    }
  });
  ctx.dispatch(VillageAccessRobbitActionCreator.refreshUI());
}

void _deleteDevice(Action action, Context<VillageAccessRobbitState> ctx) {
  YllNetwork.requestPost(VillageAction.deleteRobbit, params: action.payload,
      success: (json) {
    //{"data":"错误:版本信息缓存不存在"}
    //获取结果
    // var success = json['data'] as
    Fluttertoast.showToast(msg: '删除成功');
    var deleteId = action.payload['switchId'];
    for (var robbit in ctx.state.robbitList) {
      if (robbit.switchId == deleteId) {
        ctx.state.robbitList.remove(robbit);
        break;
      }
    }
    ctx.dispatch(VillageAccessRobbitActionCreator.refreshUI());
  }, failed: (errorCode, errorMsg) {
    Fluttertoast.showToast(msg: '$errorCode,$errorMsg');
  });
}

void _openAddingRobbitPage(
    Action action, Context<VillageAccessRobbitState> ctx) async {
  var sp = await SharedPreferences.getInstance();
  var lastVillageId = sp.getInt('lastVillage');
  Navigator.pushNamed(ctx.context, '/device_register', arguments: {
    'villageId': lastVillageId,
    'build': ctx.state.build,
    'unit': ctx.state.unit
  });
}
